/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.pc9.pswing.util;

import br.com.pc9.pswing.components.filebrowser.PFileView;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author paulocanedo
 */
public class LinuxGnomeUtil implements OperationSystemUtilInterface {

    private UserFolders userFolders;

    public LinuxGnomeUtil() {
        try {
            this.userFolders = new GnomeUserFolders();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LinuxGnomeUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LinuxGnomeUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public List<PFileView> getFavoritePlaces() throws IOException {
        File file = new File(SystemUtilsOS.getUserHomeAsFile(), ".gtk-bookmarks");
        List<PFileView> favorites = new ArrayList<PFileView>();

        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#") || line.startsWith("file://") == false) {
                    continue;
                }
                line = line.substring("file://".length());
                int indexOf = line.indexOf(" ");

                String fileLocation = null, text = null;
                if (indexOf == -1) {
                    fileLocation = line;
                    fileLocation = URLDecoder.decode(fileLocation, "utf-8");
                } else {
                    fileLocation = line.substring(0, indexOf);
                    text = line.substring(indexOf + 1);
                }
                fileLocation = URLDecoder.decode(fileLocation, "utf-8");
                favorites.add(new PFileView(new File(fileLocation), text));
            }
        } finally {
            stream.close();
        }
        return favorites;
    }

    @Override
    public UserFolders getUserFolders() {
        return userFolders;
    }
    
    private class GnomeUserFolders implements UserFolders {

        private final Properties prop = new Properties();

        public GnomeUserFolders() throws FileNotFoundException, IOException {
            File config = new File(SystemUtilsOS.getUserHomeAsFile(), ".config/user-dirs.dirs");
            StringBuilder stringProperties = new StringBuilder();
            BufferedReader reader = null;
            String line;

            reader = new BufferedReader(new FileReader(config));
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("#")) {
                    continue;
                }
                stringProperties.append(line.replaceAll("\"", "").replaceAll("\\$HOME", SystemUtilsOS.getUserHome())).append("\n");
            }
            prop.load(new ByteArrayInputStream(stringProperties.toString().getBytes()));
        }

        @Override
        public File getDocumentFolder() {
            return (new File(prop.getProperty("XDG_DOCUMENTS_DIR")));
        }

        @Override
        public File getMusicFolder() {
            return (new File(prop.getProperty("XDG_MUSIC_DIR")));
        }

        @Override
        public File getPicturesFolder() {
            return (new File(prop.getProperty("XDG_PICTURES_DIR")));
        }

        @Override
        public File getVideosFolder() {
            return (new File(prop.getProperty("XDG_VIDEOS_DIR")));
        }

        @Override
        public File getDownloadsFolder() {
            return (new File(prop.getProperty("XDG_DOWNLOAD_DIR")));
        }

        @Override
        public File getDesktopFolder() {
            return (new File(prop.getProperty("XDG_DESKTOP_DIR")));
        }

        @Override
        public File getPublicShareFolder() {
            return (new File(prop.getProperty("XDG_PUBLICSHARE_DIR")));
        }

        @Override
        public File getTemplateFolder() {
            return (new File(prop.getProperty("XDG_TEMPLATES_DIR")));
        }
    }

    @Override
    public String getThemeName() throws Exception {
//        Process exec = Runtime.getRuntime().exec("gconftool-2 -g /desktop/gnome/interface/icon_theme");
//        exec.waitFor();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
//        String themeName = reader.readLine();

        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

        File file = new File(SystemUtilsOS.getUserHomeAsFile(), ".gconf/desktop/gnome/interface/%gconf.xml");
        ThemeHandlerXml handler = new ThemeHandlerXml();
        parser.parse(file, handler);

        String themeName = handler.getThemeName();
        return themeName;
    }

    @Override
    public Icon getSystemIcon(String category, String name, int size) {
        return LinuxIconFactory.getSystemIcon(category, name, size);
    }
}

class ThemeHandlerXml extends DefaultHandler {

    private String themeName;
    private boolean iconTheme = false;
    private boolean toRead = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        String nameAttribute = attributes.getValue("name");

        toRead = iconTheme && qName.equals("stringvalue");
        if (nameAttribute != null && nameAttribute.equals("icon_theme")) {
            iconTheme = true;
        } else {
            iconTheme = false;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (toRead) {
            String value = (new String(ch, start, length));
            if (!value.trim().isEmpty()) {
                themeName = value;
            }
        }
    }

    public String getThemeName() {
        return themeName;
    }
}
